/*
通过 mutation 间接更新 state 的多个方法的对象
*/
// 接口函数
import {
  reqEvent, // 查询报警事件
  reqServiceStatistic, // 获取加油区或商超区 服务人数和服务时间
  reqStreamQuery, // 获取站点视频流地址
  reqVideoState, //获取监控视频的状态
  reqOneStream, //查询一个监控视频的信息，并请求推流
  reqLogin,
  reqLogout,
  reqRoadList,
  reqReportAlarm,
  reqVideoPingResult
} from "@/api";

import dayjs from "dayjs";
import constData from "@/util/constData";
import constData2 from "@/util/constData2";
import {
  mapTimeList,
  setToken,
  getToken
} from "../util/util";

export default {

  // 登录
  async handleLogin({
    commit
  }, params) {
    //userName = userName.trim();
    let resData = await reqLogin(params);
    return new Promise((resolve, reject) => {
      //if (userName === userInfo.userName && password === userInfo.password) {
      if (resData.code == 6000) {
        commit("setToken", resData.data.guid);
        resolve("登录成功");
      } else {
        reject("用户名或密码错误！");
      }
    });
  },
  // 退出登录
  async handleLogOut({
    commit
  }, params) {
    await reqLogout({});
    return new Promise((resolve, reject) => {
      commit("setToken", "");
      resolve();
    });
  },

  // 更新选择的站点数据
  updateSelectedStationData({
    commit
  }, selectedData) {
    // console.log('更新选择的站点数据', selectedData)
    commit("UPDATESELECTEDSTATIONDATA", {
      selectedData
    });
  },

  // 初始化所有状态数据
  initAllStateData({
    commit
  }) {
    commit("INITALLSTATEDATA");
  },

  // 获取商超区 服务人数和服务时间
  async getServiceStatistic({
    commit
  }, params) {
    let resData = await reqServiceStatistic(params); ///获取接口地址
    console.log(resData);
    if (resData.code === 9000) return;
    //let serviceGroupData = resData.data.count_group.group
    let personsGroupData = resData.data;
    // 映射的时间列表
    //let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    let timeList = mapTimeList(params.group);
    console.log("params.group::" + params.group);
    console.log("timeList::" + timeList);

    // 处理返回的数据
    let getServiceData = {
      servicePersonsSum: 0, // 服务总人次
      serviceAllTime: 0, // 收银服务总时间，总值
      serviceArgTime: 0, // 收银服务时间，平均值
      servicePersonsData: [], // 服务人次
      avgServiceTimeData: [], // 平均收银服务时间
      vehicleCongestionData: [], //车辆拥堵数据
      irregularParkingData: [], //违规停车数据
      trafficUpFlowData: [], //上行车流量
      trafficDownFlowData: [], //下行车流量
      retrogradeData: [], // 逆行数据
      slowCarsData: [], //车辆慢行
      dangerCarsData: [], //危化车辆
      //countPersons: 0
      countData: [],
      countTrafficDownFlow: 0,
      countTrafficUpFlow: 0
    };
    let countPersons = 0;
    let countIrregularCar = 0;
    let countJam = 0;
    let countSlow = 0;
    let countBack = 0;
    let countDanger = 0;
    //getServiceData.servicePersonsSum = Math.round(resData.data.e_person)
    // getServiceData.serviceAllTime = resData.data.time_all
    // getServiceData.serviceArgTime = (resData.data.count_group.average_time/60).toFixed(2)
    getServiceData.servicePersonsData = timeList.map(time => {
      return personsGroupData[time].e_person;
    });
    getServiceData.vehicleCongestionData = timeList.map(time => {
      return personsGroupData[time].e_jam;
    });

    getServiceData.irregularParkingData = timeList.map(time => {
      return personsGroupData[time].e_stop;
    });
    getServiceData.trafficUpFlowData = timeList.map(time => {
      return personsGroupData[time].upcount;
    });
    getServiceData.trafficDownFlowData = timeList.map(time => {
      return personsGroupData[time].downcount;
    });

    getServiceData.retrogradeData = timeList.map(time => {
      return personsGroupData[time].e_back;
    });
    getServiceData.slowCarsData = timeList.map(time => {
      return personsGroupData[time].e_slow;
    });
    getServiceData.dangerCarsData = timeList.map(time => {
      return personsGroupData[time].e_dc;
    });

    // countIrregularCar = 0;
    // let countJam = 0;
    // let countSlow = 0;
    // let countBack = 0;
    // let countDanger = 0;

    //计算统计总数
    //console.log("timeList.length:" + timeList.length);
    let start = 1;
    let over = timeList.length;
    if (params.group == "hour") {
      start = 0;
      over = over - 1;
    }
    for (let i = start; i <= over; i++) {
      console.log("i:" + i);
      countPersons += personsGroupData[i].e_person;
      countIrregularCar += personsGroupData[i].e_stop;
      countJam += personsGroupData[i].e_jam;
      countSlow += personsGroupData[i].e_slow;
      countBack += personsGroupData[i].e_back;
      countDanger += personsGroupData[i].e_dc;
      getServiceData.countTrafficDownFlow += personsGroupData[i].downcount;
      getServiceData.countTrafficUpFlow += personsGroupData[i].upcount;
      //console.log("countPersons:" + countPersons);
    }
    getServiceData.countData.push(countPersons);
    getServiceData.countData.push(countIrregularCar);
    getServiceData.countData.push(countJam);
    getServiceData.countData.push(countSlow);
    getServiceData.countData.push(countBack);
    getServiceData.countData.push(countDanger);
    //console.log("getServiceData.countData::" + getServiceData.countData[0]);

    // getServiceData.servicePersonsData = timeList.map((time) => {
    //    return serviceGroupData[time] ? serviceGroupData[time].total_num : 0
    //  })

    // getServiceData.avgServiceTimeData = timeList.map((time, index) => {

    //   let value = serviceGroupData[time] ? serviceGroupData[time].average_time : 0
    //   return {
    //     value: value,
    //     label: {
    //       show: index%3 === 1 && value !== 0 ? true : false
    //     }
    //   }
    // })
    // console.log('处理 商超区服务人数和服务时间 后的数据: ', getServiceData)

    commit("GETSERVICESTATISTIC", {
      getServiceData
    });
  },
  // 获取商超进店人次
  async getCustomerEnter({
    commit
  }, params) {
    let resData = await reqCustomerEnter(params);
    let customerEnterDataGroup = resData.data.count_group.group;
    // console.log('获取进店人次：', resData)
    // 映射的时间列表
    let timeList = mapTimeList(
      params.start_time,
      params.end_time,
      params.group
    );

    // 处理返回的数据
    let getCustomerEnterData = {
      enterPersonsSum: 0, // 进店总人次
      enterPersonsData: [] // 进店人次分布
    };
    getCustomerEnterData.enterPersonsSum = Math.round(resData.data.count_all);
    getCustomerEnterData.enterPersonsData = timeList.map(time => {
      return customerEnterDataGroup[time] ?
        Math.round(customerEnterDataGroup[time]) :
        0;
    });
    // console.log('处理 进店人次 后的数据：', getCustomerEnterData)

    commit("GETCUSTOMERENTER", {
      getCustomerEnterData
    });
  },
  async getQueryEventsTableData({
    commit
  }, params) {
    let resData = await reqEvent(params);
    console.log("事件：", resData);
    let eventsTableData = resData.data.events;

    let pageData = {
      //eventsTotal: resData.data.total,
      eventsPageCurrent: resData.data.index,
      eventsPageSize: resData.data.page_size,
      total_pages: resData.data.total_pages
    };

    // eventsTableData = eventsTableData.map((ele, index) => {
    //   return {
    //     index: index + 1,
    //     station: constData2.stationData[ele.station],
    //     category: constData2.categoryData[ele.category],
    //     action: ele.action,
    //     cause: ele.cause,
    //     level: constData2.levelData[ele.level],
    //     status: ele.status,
    //     datetime: ele.datetime,
    //     http_url_image: ele.http_url_image,
    //     http_url_video: ele.http_url_video,
    //     video_path: ele.video_path
    //   };
    // });

    commit("GETQUERYEVENTSTABLEDATA", {
      eventsTableData,
      pageData,
      constData2
    });
  },
  // 更新事件查询的页码
  updateEventsQueryPageIndex({
    commit
  }, currentPage) {
    commit("UPDATEEVENTSQUERYPAGEINDEX", {
      currentPage
    });
  },

  // 获取公路视频流地址
  async getAllVideoStreamUrl({
    commit,
    state
  }, switchWayNo) {
    // let highWay = 0;
    // for (let index in state.wayList) {
    //   let item = state.wayList[index]
    //   if(item.wayName == switchWayName){
    //     highWay = item.wayNo;
    //     console.log("higway:"+highWay)
    //     break;
    //   }
    // }
    let params = {
      highWay: switchWayNo
    };
    console.log("switchWayNo:" + switchWayNo)
    let resData = await reqStreamQuery(params);

    console.log("获取 站点视频流地址:", params, resData);
    if (resData.code === 6000) {
      let videoList = resData.data.video;
      // videoList.forEach(ele => {
      //   ele['title'] = constData.categoryData2[ele.category] + ele.channel + '号视频'
      // })
      // videoList = videoList.sort((a, b) => Number(b.channel)-Number(a.channel))
      // console.log('处理 站点视频流地址:',videoList)

      commit("GETALLVIDEOSTREAMURL", {
        videoList
      });
    } else {
      // 获取失败后更新获取的视频流状态，页面提示用户这个站点的流不可用
      commit("CHANGEGETVEDIOSTREAMSTATE404");
    }
  },

  // 获取公路视频流存在情况
  async getPingResults({
    commit,
  }) {
    let resData = await reqVideoPingResult({});
    let result = {};
    if (resData.code === 6000) {
      result = resData.data;
    }
    commit("GETPINGRESULTS", {
      result
    });
  },

  //获取公路视频流对应路段的监控状态信息
  async getAllVideoState({
    commit
  }, highWay) {
    let params = {
      highWay
    };
    let resData = await reqVideoState(params);

    //console.log('获取视频流状态:',params,resData)
    if (resData.code === 6000) {
      let stateList = resData.data;
      commit("GETALLVIDEOSTATE", {
        stateList
      });
    } else {
      // 获取失败后更新获取的视频流状态，页面提示用户这个站点的流不可用
      commit("CHANGEGETVEDIOSTREAMSTATE404");
    }
  },

  //获取公路某一个道路的状态信息
  async getOneVideoState({
    commit
  }, roadName) {
    let params = {
      roadName
    };
    let resData = await reqVideoState(params);
    let stateDict = {};
    //console.log('获取视频流状态:',params,resData)
    if (resData.code === 6000) {
      stateDict = resData.data;
    }
    commit("GETONEVIDEOSTATE", {
      stateDict
    });
  },

  //获取所有道路列表信息
  async getAllRoadList({
    commit
  }) {
    let resData = await reqRoadList({});
    let roadList = [];
    if (resData.code === 6000) {
      roadList = resData.data.roads;
      //console.log("roadList:", roadList);
    }
    commit("GETALLROADLIST", {
      roadList
    });
  },

  //获取所有道路列表信息2
  async getAllRoadList2({
    commit
  }) {
    let resData = await reqRoadList({});
    let roadList = [];
    if (resData.code === 6000) {
      roadList = resData.data.roads;
    }
    commit("GETALLROADLIST2", {
      roadList
    });
  },

  // 从多个视频到单个视频时，加载单个视频流实的播放页面
  async onloadVideoStreamPlayer({
    commit,
    state
  }, params) {
    let param = {
      roadName: params["roadName"]
    };
    console.log("获取视频流状态参数:", param);
    let resData = await reqVideoState(param); //加载状态，天气，速度等
    let stateDict = {};
    console.log("resData:", resData);
    if (resData.code === 6000) {
      stateDict = resData.data;
      console.log("stateDict:", stateDict);
    }
    param = {
      roadName: params["roadName"],
      highWay: params["wayNo"]
    };
    console.log("视频流推流参数:", param);
    let steamData = await reqOneStream(param);
    console.log("steamData:", steamData);
    let steamDict = {};
    if (steamData.code === 6000) {
      steamDict = steamData.data;
    }
    commit("ONLOADVIDEOSTREAMPLAYER", {
      steamDict,
      stateDict
    });
    // let resData = await reqStreamPull(params)
    // // console.log('请求到的推流信息：', resData)
    // if(resData.code === 6000) {
    //   let reqPlayerInfo = resData.data
    //   reqPlayerInfo['title'] = constData.stationList2[reqPlayerInfo.station] + constData.categoryData2[reqPlayerInfo.category] + reqPlayerInfo.channel + '号视频'

    //   commit('ONLOADVIDEOSTREAMPLAYER', { reqPlayerInfo })
    // }
  },

  // 关闭视频流详情页，打开视频流网格页面
  closeDetailsLoadVideoGridPages({
    commit
  }) {
    commit("CLOSEDETAILSLOADVIDEOGRIDPAGES");
  },
  //根据选择路段一或者路段二修改switchWay的值
  changeSwitchWay({
    commit
  }, val) {
    commit("CHANGESWITCHWAY", {
      val
    });
  },
  setLogoColor({
    commit
  }, val) {
    commit("SETLOGOCOLOR", {
      val
    });
  },
  // 首页，判断地图中那些摄像头出现事件，变为红色
  async setWarnPoint({
    commit
  }, eventList) {
    let warnRoads = []
    eventList.forEach(function (ele, index, array) {
      if (warnRoads.indexOf(ele['road_name']) === -1) {
        warnRoads.push(ele['road_name'])
      }
    });
    commit("SETWARNPOINT", {
      warnRoads
    })
  },
  // 报警器
  async reportAlarm({
    commit
  }, params) {
    let resData = await reqReportAlarm(params);
    let stateValue = {};
    if (resData.code === 6000) {
      stateValue = resData.data;
    }
    commit("REPORTALARM", {
      stateValue
    })
  }
};
